<template>
    <easy-form ref="easyFormRef" :model="model" :fieldList="fieldList" @reset-file="clearFiles" @submit="handleBaseSubmit" style="max-width: 90%; padding-left: 50px;" label-width="80px">
        <template #upload>
                <el-upload
                class="upload-demo" 
                drag 
                accept=".json"
                action="#"
                ref="uploadRef"
                :http-request="uploadFile"
                :on-remove="handleRemove"
                :auto-upload="false"
                :before-upload="beforeUpload"
                :on-change="handleChange"
                >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                     将文件拖到此处 <em>或点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">
                        仅支持上传json文件
                    </div>
                </template>
            </el-upload>
        </template>
    </easy-form>
</template>
<script lang="ts" setup>
import { taskForm } from '@/config/task'
import type { ITask } from '@/api/task';
import { TaskService } from '@/api/task';
import { message } from 'ant-design-vue';
import { UploadFilled } from '@element-plus/icons-vue'
import { UploadInstance, UploadRequestOptions } from 'element-plus';
import { FilesService } from '@/api/files';
import { UploadFile } from 'element-plus/lib/components/upload/src/upload.js';
import { RedisService } from '@/api/redis';

const props = defineProps({
    user: String,
})
const emit = defineEmits(['task-added']);

const uploadRef = ref<UploadInstance>();
const easyFormRef = ref();
let create_time : any = null;
const fieldList: Form.FieldItem[] = taskForm.base
const model = ref(<Record<string, any>>({
    test_purpose: "测试任务",
    expected_result: "无",
    product_name: "全文",
    test_environment: "武汉阅深服务器",
    test_infer: "mnn",
    modelnames: ["中文印刷", "中文手写"],
    test_data: "",
    svn: "",
    remark: "",
}))

const handleBaseSubmit = async (model: ITask) => {
    if(props.user !== undefined)
        model.task_creator = props.user
    create_time = new Date()
    model.create_time = create_time;
    uploadRef.value!.submit();
    
    await createTask(model)
    emit("task-added", file_num.value)
}

const createTask = async (model: ITask) => {
    fileList.forEach(async filename => {
        try {
            if(file_num.value > 1) {
                model.test_purpose = "批量任务_" + oldFileName.get(filename)
            }
            const data = (await TaskService.createTask(model)).data
            message.success('新增成功！')
            
            RedisService.setRedis(data.toString(), filename);
            RedisService.setRedis(filename, data.toString());
        } catch (error) {
            console.log(error)
        }
    });
}

let newFileName = "";
const file_num = ref(0)
const fileList: string[] = [];
const oldFileName = new Map<string, string>();
const beforeUpload = (file: File) => {
    const timestamp: number = Math.floor(create_time.getTime() / 1000);
    const filename = file_num.value === 0 ? timestamp.toString() : timestamp.toString() + "_" + file_num.value
    const newFile = new File([file], filename, { type: file.type });
    fileList.push(filename);
    oldFileName.set(filename, file.name.replace('.json', ''));
    file_num.value++;
    return newFile
}

const uploadFile = async (options: UploadRequestOptions) => {
    await FilesService.uploadFiles(options.file).then(res => {
        if(res.code !== 200) 
            message.error('上传失败！')
    }).catch(error => {
        console.error(error)
    });
}

const handleRemove = () => {
    if(newFileName){
        FilesService.deleteFile(newFileName).catch(error => {
            console.error(error)
        })
    }
}

const handleChange = (uploadFile: UploadFile) => {
    easyFormRef.value.formModel.file = uploadFile
    easyFormRef.value.formRef.validateField().catch(() => {})
}


const clearFiles = () => {
    uploadRef.value!.clearFiles()
}



</script>
<style lang="scss" scoped>
::v-deep .el-upload-dragger {
    width: 250px;
    height: 110px;
    padding: 0%;
}

::v-deep .el-upload__text {
    background-color: rgb(227, 230, 228);
    margin-top: -5px;
}

::v-deep .el-icon{
    color: rgb(128, 202, 138);
}

</style>
